package com.example.fw;

import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;

public class HelperWithWebDriverBase extends HelperBase {

	protected WebDriver driver;
	protected static String baseUrl;	// = manager.getProperty("baseUrl")

	public HelperWithWebDriverBase(ApplicationManager manager) {
		super(manager);
		//this.manager = manager;							// appeared after Assign parameter to new field
		driver = manager.getWebDriverHelper().getDriver();					// Create field 'driver'
		//baseUrl = WebDriverHelper.baseUrl; 	//"http://localhost:8080";
	}

	void type(By locator, String name) {
		findElement(locator).clear();
		findElement(locator).sendKeys(name);
	}

	void select(By locator, String optionText) {
		new Select(driver.findElement(locator)).selectByVisibleText(optionText);
	}

	void selectRandom(By locator) {
		Select select = new Select(driver.findElement(locator));
		List<WebElement> options = select.getOptions();
		if (options.size() > 0)	{
			int index = new Random().nextInt(options.size());
			options.get(index).click();
		}
	}

//	protected boolean isElementPresent(By by) {
//		try {
//			driver.findElement(by);
//			return true;
//		} catch (NoSuchElementException e) {
//			return false;
//		}
//	}

//	avoid delay if no objects in list
	
	public boolean isElementPresent(By locator) {
	    driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
	    boolean verdict = driver.findElements(locator).size() > 0;
	    driver.manage().timeouts().implicitlyWait(
	    		Integer.parseInt(manager.getProperty("implicitWait", "20")), TimeUnit.SECONDS);
	    return verdict;
	}	

	protected WebElement findElement(By locator) {
		return driver.findElement(locator);
	}

	protected List<WebElement> findElements(By locator) {
		return driver.findElements(locator);
	}

	protected void openUrl(String string) {
		driver.get(manager.getProperty("baseUrl") + string);
	}

	protected void openAbsoluteUrl(String string) {
		driver.get(string);
	}
	
	protected void click(By locator) {
		findElement(locator).click();
	}

	protected void pause(int pause) {
		try {
			Thread.sleep(pause);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}